package com.leet.tree;

import java.util.Arrays;

public class BuildTreeByInAndPost {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        // buildTree默公式
        if(inorder.length == 0 || postorder.length == 0){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postorder.length-1]);
        for(int i = 0 ; i < inorder.length; i++){
            if(inorder[i] == root.val){
                int[] p_l = Arrays.copyOfRange(postorder,0,i);
                int[] p_r = Arrays.copyOfRange(postorder,i,postorder.length-1);
                int[] i_l = Arrays.copyOfRange(inorder,0,i);
                int[] i_r = Arrays.copyOfRange(inorder,i+1,inorder.length);
                root.left = buildTree(i_l,p_l);
                root.right = buildTree(i_r,p_r);
                break;
            }
        }
        return root;
    }
}
